import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title

  // determine whether the user has logged in
  // document.title = '优点达--' + to.meta.title
  document.title = getPageTitle(to.meta.title)
  if (store.getters.token) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      Message({
        message: '请勿重复登录',
        type: 'warning'
      })
      NProgress.done()
    } else {
      if (!store.getters.userId) {
        const menuList = await store.dispatch('user/getInfo')
        console.log(menuList)
        const finallyroutes = await store.dispatch('user/getnewroute', menuList)
        console.log(finallyroutes)
        finallyroutes.push({ path: '*', redirect: '/404', hidden: true })
        store.commit('user/setrouter', finallyroutes)
        router.addRoutes(finallyroutes)
        next(to.path)
      } else {
        next()
      }
    }
  } else {
    /* has no token*/

    if (whiteList.includes(to.path)) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
